﻿using System.Reflection.Metadata;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Collections;
using System.Reflection;
using UMC.Web;
using UMC.Data.Entities;
using UMC.Web.UI;
using UMC.ITME.Entities;
using UMC.Net;
using UMC.Data;
using SkiaSharp;

namespace UMC.ITME.Activities
{
    /// <summary>
    /// 应用安装
    /// </summary>
    [UMC.Web.Apiumc("ITME", "Setup", Auth = WebAuthType.Admin)]
    class SiteSetupActivity : WebActivity
    {

        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var ConfKey = this.AsyncDialog("ConfKey", r =>
            {
                return new Web.UISheetDialog() { Title = "新发布类型" }
                .Put("Web应用", "Proxy").Put("文件应用", "File");
            });
            if (ConfKey.StartsWith("https://") || ConfKey.StartsWith("http://"))
            {
                var url = new Uri(ConfKey);
                request.Arguments.Put("Domain", new Uri(url, "/").AbsoluteUri);
                ConfKey = url.LocalPath.Trim('/');
                if (String.IsNullOrEmpty(ConfKey) == false)
                {
                    request.Arguments.Put("ConfKey", ConfKey);
                }
                else
                {
                    request.Arguments.Put("ConfKey", "Proxy");
                }
            }
            var appId = UMC.Data.WebResource.Instance().Provider["appId"];
            var secret = UMC.Data.WebResource.Instance().Provider["appSecret"];

            var config = this.AsyncDialog("Settings", g =>
            {
                var from = new Web.UIFormDialog() { Title = "发布新应用" };
                var sDomain = this.AsyncDialog("Domain", "none");

                switch (ConfKey)
                {
                    case "UMC":
                    case "Proxy":
                    case "Bridge":
                        if (String.Equals(sDomain, "none"))
                        {
                            from.AddText("应用网址", "Domain", String.Empty);
                            this.Context.Request.Arguments.Remove("Domain");
                        }
                        else
                        {
                            from.AddTextValue().Put("应用网址", sDomain);
                        }
                        from.AddText("发布标识", "Root", String.Empty).PlaceHolder("[a-z0-9]全小写字符").Put("tip", "");// $"将以[标识]为前缀合成域名来访问");
                        from.AddText("发布名称", "Caption", String.Empty);
                        break;

                    case "File":
                        this.Context.Request.Arguments.Remove("Domain");
                        from.Title = "发布文件应用";
                        from.AddOption("所在目录", "Domain", String.Empty, String.Empty).Command("System", "Dir", new WebMeta().Put("type", "Dir"));

                        from.AddText("发布标识", "Root", String.Empty).PlaceHolder("[a-z0-9]全小写字符").Put("tip", "");//$"将以[标识]为前缀合成域名来访问");
                        from.AddText("发布名称", "Caption", String.Empty);
                        from.AddCheckBox("", "AuthConf", "none").Put("支持目录浏览", "*", true);
                        break;
                    case "Developer":
                        if (String.IsNullOrEmpty(secret))
                        {
                            this.Context.Response.Redirect("System", "License", new UIConfirmDialog("当前版本未登记注册") { DefaultValue = "Select" });
                        }
                        from.Title = "开发者发布";

                        from.Add(new UIQRCode($"https://api.apiumc.com/UMC/Platform/EditCert/{appId}"));
                        from.AddFooter("请开发者用ITME App扫一扫，生成开发者证书，再点击下一步", "Settings", "YES");

                        from.Submit("下一步", $"{request.Model}.{request.Command}");
                        return from;

                    default:
                        if (String.IsNullOrEmpty(secret))
                        {
                            this.Context.Response.Redirect("System", "License", new UIConfirmDialog("当前版本未登记注册") { DefaultValue = "Select" });
                        }
                        var webr2 = new Uri(APIProxy.Uri, "Transfer").WebRequest();
                        UMC.ITME.Utility.Sign(webr2, secret);
                        var data = JSON.Deserialize<System.Collections.Hashtable>(webr2.Post(new WebMeta().Put("type", "Market", "ProductCode", ConfKey), out var _));
                        if (data == null)
                        {
                            request.Arguments.Put("ConfKey", "Proxy");
                            goto case "UMC";

                        }
                        if (data.ContainsKey("success"))
                        {
                            from.Title = "发布市场应用";
                            if (data.ContainsKey("Domain"))
                            {
                                sDomain = data["Domain"] as string;
                                this.Context.Request.Arguments.Put("Domain", sDomain);
                                from.AddTextValue().Put("服务网址", sDomain);

                            }
                            else if (String.Equals(sDomain, "none"))
                            {
                                from.AddText("应用网址", "Domain", String.Empty);
                                this.Context.Request.Arguments.Remove("Domain");
                            }
                            else
                            {
                                if (sDomain.Contains("\n"))
                                {
                                    from.AddTextValue().Put("应用网址", sDomain.Split('\n')[0]);
                                }
                                else
                                {

                                    from.AddTextValue().Put("应用网址", sDomain);
                                }
                            }
                            if (data.ContainsKey("IconSrc"))
                            {
                                this.Context.Request.Arguments.Put("IconSrc", data["IconSrc"]);
                            }

                            from.AddText("发布标识", "Root", String.Empty).PlaceHolder("[a-z0-9]全小写字符").Put("tip", "");//$"将以[标识]为前缀合成域名来访问");
                            from.AddText("发布名称", "Caption", data["Caption"] as string);

                            from.AddRadio("服务条款", "Price", new ListItemCollection().Put(String.Format("{0}", data["Price"]), "1"));

                            from.Submit("确认发布", "Site.Config");
                            from.Add(UICell.UI('\uf085', "开发者", data["Seller"] as string));

                            from.Add(UICell.UI('\ue94d', "服务电话", data["Tel"] as string, UIClick.Tel(data["Tel"] as string)));
                            return from;
                        }
                        else
                        {
                            request.Arguments.Put("ConfKey", "Proxy");
                            goto case "UMC";

                        }
                        // break;
                }
                from.Submit("确认发布", "Site.Config");
                return from;
            });
            if (ConfKey == "Developer")
            {

                var content = new Uri($"https://wdk.oss-accelerate.aliyuncs.com/TEMP/EditCert/{appId}.lic").WebRequest().Get(out var _);//.ReadAsString();

                if (String.IsNullOrEmpty(content))
                {
                    this.Prompt("获取证书失败");
                }
                var s = content.IndexOf(":");
                if (s == -1)
                {
                    this.Prompt("获取证书失败");

                }
                var Seller = content.Substring(0, s);

                if (License.GetLicense(Seller).ExpireTime > 0 || License.Put(Seller, content.Substring(s + 1)))
                {
                    this.Context.Send(false);
                    response.Redirect(request.Model, request.Command, Seller);
                    this.Prompt("证书导入成功");
                }
                else
                {
                    this.Prompt("获取导入失败,请确认证书是否一致");
                }
            }
            var site = new Site
            {
                Root = config["Root"].ToLower()
            };
            if (System.Text.RegularExpressions.Regex.IsMatch(site.Root, "^[a-z0-9]+$") == false)
            {
                this.Prompt("应用标识只支持【a-z0-9】字符");
            }
            site.Caption = config["Caption"];
            try
            {
                var Domain = config["Domain"];
                if (String.IsNullOrEmpty(Domain))
                {
                    this.Prompt("请输入正确的网址");
                }

                switch (Domain.Substring(0, Domain.IndexOf("://")))
                {
                    case "http":
                    case "https":
                        if (Domain.Contains("*."))
                        {
                            var l = Domain.IndexOf('/', 8);
                            if (l == -1)
                            {
                                site.Domain = Domain + "/";
                            }
                            else
                            {
                                site.Domain = Domain.Substring(0, l + 1);

                            }
                            if (ConfKey == "Proxy")
                            {
                                ConfKey = "Wildcard";
                            }
                        }
                        else
                        {
                            var orgDomain = new Uri(Domain);
                            if (ConfKey == "Proxy")
                            {
                                if (orgDomain.LocalPath.Trim('/') == "UMC")
                                {
                                    ConfKey = "UMC";
                                }
                            }
                            if (ConfKey == "UMC")
                            {
                                Domain = new Uri(orgDomain, "/").AbsoluteUri;//
                                this.Context.Request.Arguments.Put("ConfKey", "UMC");
                                this.Context.Request.Arguments.Put("Domain", Domain);
                                var str = new Uri(orgDomain, "/UMC/Conf").WebRequest().Put(new WebMeta().Put("domain", $"{Web.WebResource.Instance().WebDomain()}"), out var _);
                                var data = JSON.Deserialize<System.Collections.Hashtable>(str);
                                if (data?.ContainsKey("appConf") == true)
                                {
                                    var appConf = data["appConf"] as Hashtable;
                                    if (appConf.ContainsKey("IconSrc"))
                                    {
                                        this.Context.Request.Arguments.Put("IconSrc", appConf["IconSrc"]);
                                        config.Put("IconSrc", appConf["IconSrc"]);
                                    }
                                    if (appConf.ContainsKey("MarketKey"))
                                    {
                                        site.AuthConf = "#";
                                        site.UserModel = UserModel.Bridge;
                                        site.AuthType = WebAuthType.Guest;
                                        ConfKey = appConf["MarketKey"] as string;
                                    }


                                    if (appConf.ContainsKey("Open"))
                                    {
                                        this.Context.Request.Arguments.Put("Open", appConf["Open"]);
                                        config.Put("Open", appConf["Open"]);
                                    }
                                    if (appConf.ContainsKey("Menu"))
                                    {
                                        this.Context.Request.Arguments.Put("Menu", JSON.Serialize(appConf["Menu"]));
                                        config.Put("Menu", appConf["Menu"]);
                                    }
                                    if (appConf.ContainsKey("Home"))
                                    {
                                        this.Context.Request.Arguments.Put("Home", appConf["Home"]);
                                        config.Put("Home", appConf["Home"]);
                                    }
                                    if (appConf.ContainsKey("Mobile"))
                                    {
                                        this.Context.Request.Arguments.Put("Mobile", appConf["Mobile"]);
                                        config.Put("Mobile", appConf["Mobile"]);

                                    }

                                }

                            }
                            site.Domain = new Uri(orgDomain, "/").AbsoluteUri;

                        }
                        break;
                    case "file":
                        site.Domain = Domain.TrimEnd('/');
                        if (config["AuthConf"].Contains("*"))
                        {
                            site.Domain += "/";
                        }
                        break;
                    case "unix":
                        site.Domain = Domain;
                        break;
                    default:
                        this.Prompt("网址格式不支持");
                        break;
                }
            }
            catch
            {
                this.Prompt("网址格式不支持");
            }

            if (config.ContainsKey("Home"))
            {
                site.Home = config["Home"];
            }

            if (config.ContainsKey("Mobile"))
            {
                site.MobileHome = config["Mobile"];
            }

            if (config.ContainsKey("Open"))
            {
                switch (config["Open"].ToLower())
                {
                    default:
                    case "new":
                        site.OpenModel = 0;
                        break;
                    case "win":
                        site.OpenModel = 1;
                        break;
                    case "mac":
                        site.OpenModel = 2;
                        break;
                    case "link":
                        site.OpenModel = 3;
                        break;
                }
            }
            if (config.ContainsKey("Menu"))
            {
                var lis = new List<Menu>();
                var meus = JSON.Deserialize(config["Menu"]);
                var tid = Utility.TimeSpan();
                if (meus is IDictionary)
                {
                    var l = new Menu();
                    Reflection.SetProperty(l, meus as IDictionary);
                    if (l.Id.HasValue)
                    {
                        l.Id = tid + 1;
                    }
                    l.Site = 0;
                    lis.Add(l);

                }
                else if (meus is Array)
                {
                    var ms = meus as Array;
                    foreach (var o in ms)
                    {
                        if (o is IDictionary)
                        {
                            var l = new Menu();
                            Reflection.SetProperty(l, o as IDictionary);
                            if (l.Id.HasValue)
                            {
                                l.Id = tid + 1;
                            }
                            l.Site = 0;
                            lis.Add(l);

                        }
                    }
                }

                Data.DataFactory.Instance().Put(lis.ToArray());
            }

            site.SiteKey = UMC.Data.Utility.IntParse(UMC.Data.Utility.Guid(site.Root, true).Value);
            site.IsDesktop = true;
            var oldSite = DataFactory.Instance().Site(site.Root);
            if (oldSite != null)
            {
                if (oldSite.Flag < 0)
                {
                    this.AsyncDialog("Confirm", g => new Web.UIConfirmDialog("此标识存在于移除的应用中，是否恢复此应用来从新设置") { Title = "应用提示" });
                    DataFactory.Instance().Put(new Site { Root = site.Root, Flag = 0 });
                    this.Context.Send("Site.Config", false);
                    this.Context.Response.Redirect(this.Context.Request.Model, this.Context.Request.Command, site.Root);
                }
                else
                {
                    switch (ConfKey)
                    {
                        case "UMC":
                        case "Bridge":
                        case "File":
                        case "Proxy":
                            this.Prompt("此应用标识已注册");
                            break;
                        default:
                            this.AsyncDialog("Confirm", g => new Web.UIConfirmDialog($"确认在{oldSite.Caption}安装此应用配置，将有覆盖现有配置") { Title = "应用提示" });
                            break;
                    }
                }
            }
            site.Seq = Utility.TimeID();

            switch (ConfKey)

            {
                case "Proxy":
                    site.AuthType = WebAuthType.All;
                    if (String.IsNullOrEmpty(site.HostReConf))
                    {
                        site.HostReConf = "Redirect rp\ntext/html rp\ntext/plain rp\ntext/javascript rp\napplication/json rp\napplication/javascript rp\napplication/x-javascript rp";
                    }
                    break;
                case "Wildcard":
                    site.AuthType = WebAuthType.All;
                    if (String.IsNullOrEmpty(site.HostReConf))
                    {
                        site.HostReConf = "Redirect rp\ntext/html rp\ntext/plain rp\ntext/javascript rp\napplication/json rp\napplication/javascript rp\napplication/x-javascript rp";
                    }
                    break;
                case "File":
                    site.AuthType = WebAuthType.Guest;
                    break;
                case "UMC":
                    site.AuthConf = "#";
                    site.UserModel = UserModel.Bridge;
                    site.AuthType = WebAuthType.Guest;
                    break;
                case "Bridge":
                    site.AuthConf = String.Empty;
                    site.UserModel = UserModel.Bridge;
                    site.AuthType = WebAuthType.Guest;

                    if (String.IsNullOrEmpty(site.HostReConf) == false)
                    {
                        site.HostReConf = "Redirect rp\ntext/html rp\ntext/plain rp\ntext/javascript rp\napplication/json rp\napplication/javascript rp\napplication/x-javascript rp";
                    }
                    break;

                default:
                    var json = UMC.ITME.Utility.Sign(new Uri(APIProxy.Uri, "Transfer").WebRequest(), secret).Post(new WebMeta().Put("type", "Market", "ConfKey", ConfKey, "Root", site.Root), out var _);
                    var data = JSON.Deserialize<System.Collections.Hashtable>(json);
                    if (data.ContainsKey("success"))
                    {
                        if (data.ContainsKey("Domain"))
                        {
                            site.Domain = data["Domain"] as String;
                        }
                        if (data.ContainsKey("UserModel"))
                        {
                            site.UserModel = Utility.Parse(data["UserModel"] as String, UserModel.Standard);
                        }
                        if (data.ContainsKey("AuthType"))
                        {
                            site.AuthType = Utility.Parse(data["AuthType"] as String, WebAuthType.All);
                        }
                        if (data.ContainsKey("HostReConf"))
                        {
                            site.HostReConf = data["HostReConf"] as String;
                        }
                        if (data.ContainsKey("AuthConf"))
                        {
                            site.AuthConf = data["AuthConf"] as String;
                        }
                        site.MarketKey = data["MarketKey"] as string;

                        if (data.ContainsKey("appConf"))
                        {
                            var appConf = data["appConf"] as Hashtable;
                            appConf.Remove("Root");
                            appConf.Remove("Domain");
                            appConf.Remove("Caption");
                            UMC.Data.Reflection.SetProperty(site, appConf);
                            var appendJSConf = appConf["appendJsConf"] as Hashtable;
                            if (appendJSConf != null)
                            {
                                var em = appendJSConf.GetEnumerator();

                                var jsConf = new System.Text.StringBuilder();
                                while (em.MoveNext())
                                {
                                    jsConf.Append(em.Key);
                                    jsConf.AppendLine();

                                    Config pconfig = new Config();
                                    var md5Key = SiteActivity.MD5(em.Key as string);

                                    pconfig.ConfKey = String.Format("SITE_JS_CONFIG_{0}{1}", site.Root, md5Key).ToUpper();
                                    pconfig.ConfValue = new StringValue((em.Value as string).UTF8());
                                    UMC.Data.DataFactory.Instance().Put(pconfig);
                                }
                                site.AppendJSConf = jsConf.ToString();
                            }
                            var configImage = appConf["confImage"] as Hashtable;
                            if (configImage != null)
                            {
                                var em = configImage.GetEnumerator();

                                var jsConf = new System.Text.StringBuilder();
                                while (em.MoveNext())
                                {
                                    jsConf.Append(em.Key);
                                    jsConf.AppendLine();

                                    Config pconfig = new Config();
                                    var md5Key = SiteActivity.MD5(em.Key as string);

                                    pconfig.ConfKey = String.Format("SITE_IMAGE_CONFIG_{0}{1}", site.Root, md5Key).ToUpper();
                                    pconfig.ConfValue = new StringValue(JSON.Serialize(em.Value).UTF8());
                                    UMC.Data.DataFactory.Instance().Put(pconfig);
                                }
                                site.ImagesConf = jsConf.ToString();
                            }

                            if (appConf.ContainsKey("loginHtml"))
                            {
                                Config pconfig = new Config
                                {
                                    ConfKey = $"SITE_MIME_{site.Root}_LOGIN_HTML".ToUpper(),
                                    ConfValue = new StringValue((appConf["loginHtml"] as string).UTF8())
                                };
                                UMC.Data.DataFactory.Instance().Put(pconfig);
                            }
                            if (appConf.ContainsKey("resblock"))
                            {
                                Config pconfig = new Config
                                {
                                    ConfKey = $"SITE_RES_BLOCK_{site.Root}".ToUpper(),
                                    ConfValue = new StringValue((appConf["resblock"] as string).UTF8())
                                };
                                UMC.Data.DataFactory.Instance().Put(pconfig);
                            }

                            if (appConf.ContainsKey("proxy"))
                            {
                                site.Type = ((site.Type ?? 0) | 2048);
                                var proxy = appConf["proxy"] as Hashtable;
                                if (proxy != null)
                                {
                                    var em = proxy.GetEnumerator();
                                    while (em.MoveNext())
                                    {
                                        var domain = new StringValue(em.Key as string);
                                        var value = em.Value as string;
                                        var values = Utility.FromBase64String(value);
                                        var proxySite = HotCache.Get(new ProxySite() { Domain = domain });
                                        if (proxySite == null)
                                        {

                                            proxySite = new ProxySite() { Domain = domain };
                                            if (value.Length % 2 > 0)
                                            {
                                                proxySite.Type = 1.StringValue();
                                                proxySite.ProxyIP = new StringValue(values, 0, values.Length - 1);
                                            }
                                            else
                                            {
                                                proxySite.Type = 0.StringValue();
                                                proxySite.ProxyIP = new StringValue(values);//, 0, values.Length - 1);

                                            }
                                            proxySite.ConfigKey = site.SiteKey.Value.StringValue();

                                            HotCache.Put(proxySite);

                                            // proxySite = new ProxySite { Domain = new StringValue(host), ConfigKey = site.SiteKey.Value.StringValue(), ProxyType = ProxyType.StringValue(), Type = type.StringValue() };
                                        }
                                        else
                                        {
                                            if (proxySite.ConfigKey.Contains(site.SiteKey.Value.StringValue().Span) == false)
                                            {
                                                var bus = new byte[proxySite.ConfigKey.Length + 4];
                                                proxySite.ConfigKey.Span.CopyTo(bus);
                                                BitConverter.TryWriteBytes(bus.AsSpan(proxySite.ConfigKey.Length), site.SiteKey.Value);// site.SiteKey.Value.StringValue().p
                                                proxySite.ConfigKey = new StringValue(bus);

                                                HotCache.Put(proxySite);
                                            }

                                        }
                                    }


                                }
                            }
                            if (appConf.ContainsKey("login"))
                            {
                                CopyMime(appConf["login"] as Hashtable, $"SITE_MIME_{site.Root}_LOGIN".ToUpper());
                            }
                            if (appConf.ContainsKey("check"))
                            {
                                CopyMime(appConf["check"] as Hashtable, $"SITE_MIME_{site.Root}_CHECK".ToUpper());
                            }
                            if (appConf.ContainsKey("update"))
                            {
                                CopyMime(appConf["update"] as Hashtable, $"SITE_MIME_{site.Root}_UPDATE".ToUpper());
                            }
                        }
                        site.Flag = 2;
                        if (data.ContainsKey("sign"))
                        {
                            License.Put(site.MarketKey, data["sign"] as string);
                        }

                    }
                    else
                    {
                        this.Prompt("提示", data["msg"] as string ?? "导入配置错误");
                    }

                    break;
            }

            if (config.ContainsKey("IconSrc"))
            {
                UMC.Data.WebResource.Instance().Transfer(new Uri(config["IconSrc"] as string), $"images/{site.Root}/1/0.png");
            }
            else
            {
                var file = UMC.Data.Reflection.ConfigPath(String.Format("Static\\TEMP\\{0}", site.Root));

                var image = new SKBitmap(200, 200);
                var templateG = new SKCanvas(image);
                using (SKPaint paint = new SKPaint())
                {
                    var cs = new String[] { "#63b359", "#2c9f67", "#509fc9", "#5885cf", "#9062c0", "#d09a45", "#e4b138", "#ee903c", "#f08500", "#a9d92d", "#dd6549", "#cc463d", "#cf3e36", "#5E6671" };

                    paint.Color = SKColor.Parse(cs[Math.Abs(site.SiteKey.Value % cs.Length)]);
                    templateG.DrawRect(SKRect.Create(new SKPoint(0, 0), new SKSize(200, 200)), paint);
                    //    


                    var value = site.Caption.Substring(0, 1);
                    if (value[0] < 256)
                    {
                        if (site.Caption.Length > 1)
                        {
                            value = site.Caption.Substring(0, 2);
                        }
                        value = value.ToUpper();
                    }
                    using SKTypeface sKTypeface = SKTypeface.FromFamilyName(SKFontManager.Default.FontFamilies.FirstOrDefault(r => String.Equals("WenQuanYi Zen Hei", r) || String.Equals("Arial Unicode MS", r)) ?? SKTypeface.Default.FamilyName);


                    using SKFont font = new SKFont(sKTypeface, 100);
                    using SKPaint sKPaint = new SKPaint(font);
                    sKPaint.Color = SKColor.Parse("#fff");
                    sKPaint.IsAntialias = true;
                    sKPaint.TextAlign = SKTextAlign.Center;
                    templateG.DrawText(value, 100, 140, sKPaint);
                    var output = Utility.Writer(file, false);
                    image.Encode(output, SKEncodedImageFormat.Png, 80);
                    output.Close();

                }

                String webrkey = String.Format("images/{0}/{1}/{2}.png", site.Root, 1, 0);
                UMC.Data.WebResource.Instance().Transfer(new Uri($"file://{file}"), webrkey);
            }
            Save(site);

        }
        void Save(Site site)
        {
            site.AppSecret = Utility.Guid(Guid.NewGuid());
            DataFactory.Instance().Put(site);
            this.Prompt("发布应用成功", false);
            this.Context.Send("Site.Config.Add", false);
            this.Context.Send("Site.Config", false);
            if (site.UserModel == UserModel.Bridge && String.Equals(site.AuthConf, "#"))
            {
                new Uri(new Uri(site.Domain), "/UMC.Conf").WebRequest().Put(new WebMeta().Put("authSecret", site.AppSecret).Put("domain", $"{Web.WebResource.Instance().WebDomain()}"), r => { });//

                this.Context.Response.Redirect(this.Context.Request.Model, "UMC", site.Root);
            }
            else
            {
                this.Context.Response.Redirect(this.Context.Request.Model, "Site", site.Root);
            }
        }
        void CopyMime(Hashtable config, String key)
        {
            var array = config["Feilds"] as Hashtable;
            var fConfig = new Hashtable();
            if (array != null)
            {
                var em = array.GetEnumerator();
                while (em.MoveNext())
                {
                    var fConf = em.Value as Hashtable;
                    fConfig[em.Key] = fConf["Caption"];
                    fConf.Remove("Caption");
                    if (fConf.Count > 0)
                    {
                        var fconfig2 = new Config
                        {
                            ConfKey = $"{key}_{em.Key}".ToUpper(),
                            ConfValue = new StringValue(JSON.Serialize(fConf).UTF8())
                        };
                        UMC.Data.DataFactory.Instance().Put(fconfig2);
                    }
                }
                config["Feilds"] = fConfig;
            }

            var fconfig = new Config
            {
                ConfKey = key.ToUpper(),
                ConfValue = new StringValue(JSON.Serialize(config).UTF8())
            };
            UMC.Data.DataFactory.Instance().Put(fconfig);
        }
    }
}